from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
import json


@csrf_exempt
@require_http_methods(["POST"])
def user_register(request):
    """
    用户注册接口
    POST /mentorx/auth/register/
    """
    try:
        data = json.loads(request.body)
        
        username = data.get('username')
        password = data.get('password')
        
        if not username or not password:
            return JsonResponse({
                'success': False,
                'message': '用户名和密码不能为空'
            }, status=400)
        
        if len(username) < 3 or len(username) > 150:
            return JsonResponse({
                'success': False,
                'message': '用户名长度3-150个字符'
            }, status=400)
        
        if len(password) < 6:
            return JsonResponse({
                'success': False,
                'message': '密码至少需要6个字符'
            }, status=400)
        
        if User.objects.filter(username=username).exists():
            return JsonResponse({
                'success': False,
                'message': '用户名已存在'
            }, status=400)
        
        user = User.objects.create_user(
            username=username,
            password=password,
            email=data.get('email', '')
        )
        
        login(request, user)
        
        return JsonResponse({
            'success': True,
            'message': '注册成功',
            'data': {
                'id': user.id,
                'username': user.username,
                'email': user.email
            }
        }, status=201)
        
    except json.JSONDecodeError:
        return JsonResponse({
            'success': False,
            'message': 'JSON格式错误'
        }, status=400)
    except Exception as e:
        return JsonResponse({
            'success': False,
            'message': f'注册失败: {str(e)}'
        }, status=500)


@csrf_exempt
@require_http_methods(["POST"])
def user_login(request):
    """
    用户登录接口
    POST /mentorx/auth/login/
    """
    try:
        data = json.loads(request.body)
        
        username = data.get('username')
        password = data.get('password')
        
        if not username or not password:
            return JsonResponse({
                'success': False,
                'message': '用户名和密码不能为空'
            }, status=400)
        
        user = authenticate(request, username=username, password=password)
        
        if user is not None:
            if user.is_active:
                login(request, user)
                
                return JsonResponse({
                    'success': True,
                    'message': '登录成功',
                    'data': {
                        'id': user.id,
                        'username': user.username,
                        'email': user.email,
                        'is_staff': user.is_staff,
                        'is_superuser': user.is_superuser
                    }
                })
            else:
                return JsonResponse({
                    'success': False,
                    'message': '用户账户已被禁用'
                }, status=400)
        else:
            return JsonResponse({
                'success': False,
                'message': '用户名或密码错误'
            }, status=401)
            
    except json.JSONDecodeError:
        return JsonResponse({
            'success': False,
            'message': 'JSON格式错误'
        }, status=400)
    except Exception as e:
        return JsonResponse({
            'success': False,
            'message': f'登录失败: {str(e)}'
        }, status=500)


@csrf_exempt
@require_http_methods(["POST"])
def user_logout(request):
    """
    用户登出接口
    POST /mentorx/auth/logout/
    """
    try:
        logout(request)
        return JsonResponse({
            'success': True,
            'message': '登出成功'
        })
    except Exception as e:
        return JsonResponse({
            'success': False,
            'message': f'登出失败: {str(e)}'
        }, status=500)


@csrf_exempt
@require_http_methods(["GET"])
def user_info(request):
    """
    获取当前用户信息
    GET /mentorx/auth/user/
    """
    try:
        if not request.user.is_authenticated:
            return JsonResponse({
                'success': False,
                'message': '用户未登录'
            }, status=401)
        
        user = request.user
        return JsonResponse({
            'success': True,
            'data': {
                'id': user.id,
                'username': user.username,
                'email': user.email,
                'is_staff': user.is_staff,
                'is_superuser': user.is_superuser
            }
        })
    except Exception as e:
        return JsonResponse({
            'success': False,
            'message': f'获取用户信息失败: {str(e)}'
        }, status=500)
